package com.longlong.server;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;

/**
 * 处理请求信息
 * 发送响应信息
 *
 * @author longlong
 */
@Slf4j
public class ServerHandler extends Thread {

    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // 通过 socket 读取消息
        String message = this.receiveRequest();
        // 解析消息
        HttpServletRequest request = this.parseContentAndParams(message);
        // 处理请求
        HttpServletResponse response = new HttpServletResponse();
        ServletController.findController(request, response);
        // 发送响应信息
        this.responseToBrowser(response);
    }

    /**
     * 读取消息
     */
    private String receiveRequest() {
        String contentAndParams = null;
        try {
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);
            // 读取消息 content?key=value&key=value
            contentAndParams = reader.readLine();
            log.info("receive request :{}", contentAndParams);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return contentAndParams;
    }

    /**
     * 解析消息
     */
    private HttpServletRequest parseContentAndParams(String contentAndParams) {
        String content;
        HashMap<String, String> paramsMap = null;
        // content?key=value&key=value
        // 找寻问号所在的位置
        int questionMarkIndex = contentAndParams.indexOf("?");
        // 判断是否携带了参数
        if (questionMarkIndex != -1) {
            // 携带了参数 截取问号前面的信息-->请求资源名 问号后面的信息拆分存入map集合里
            content = contentAndParams.substring(0, questionMarkIndex);
            paramsMap = new HashMap<>(10);
            // 处理问号后面的参数 拆分存入map集合   key=value&key=value
            String params = contentAndParams.substring(questionMarkIndex + 1);
            String[] keyAndValues = params.split("&");
            for (String keyAndValue : keyAndValues) {
                String[] KV = keyAndValue.split("=");
                paramsMap.put(KV[0], KV[1]);
            }
        } else {
            // 没有携带参数 请求发过来的信息就是完整的资源名
            content = contentAndParams;
        }
        log.info("content:{},params:{}", content, paramsMap);
        // 封装成 HttpServletRequest 对象
        HttpServletRequest request = new HttpServletRequest();
        request.setContent(content);
        request.setParamsMap(paramsMap);
        return request;
    }

    /**
     * 发送最终的响应信息
     */
    private void responseToBrowser(HttpServletResponse response) {
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            out.println(response.getResponseContent());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
